<template>
  <a-spin class="anchor-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l search-box">
        <div>
          <span>SPU审核状态：</span>
          <a-select style="width:160px;" placeholder="请选择状态" v-model="search.spuStatus" @change="handleByQueryCond">
            <a-select-option v-for="item in spuStatusList" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>高德ID：</span>
          <a-input-search style="width:160px;" type="text" placeholder="高德ID" allowClear v-model="search.gdId" @search="handleByQueryCond" />
        </div>
        <div>
          <span>门店地址：</span>
          <a-input-search style="width:160px;" type="text" placeholder="门店地址" allowClear v-model="search.address" @search="handleByQueryCond" />
        </div>
        <div>
          <span>门店名称：</span>
          <a-input-search style="width:160px;" type="text" placeholder="门店名称" allowClear v-model="search.name" @search="handleByQueryCond" />
        </div>
      </div>
      <div class="r" style="width:300px;justify-content: flex-end;display:flex">
        <a-dropdown placement="bottomLeft">
          <a-button type="primary">操作按钮集合<a-icon type="down"/></a-button>
          <a-menu slot="overlay">
            <a-menu-item>
              <a-button type="link" @click="handleOpenBind">新增绑定</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="batchSubmission">批量提交审核</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="handleGoods({}, 1, 1)">批量上架</a-button>
            </a-menu-item>
            <a-menu-item>
              <a-button type="link" @click="handleGoods({}, 0, 1)">批量下架</a-button>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <AddSpuModal @close="handleCloseModal" @updateList="handleUpdateList" :visible="visible" />
    <!-- 表格 -->
    <div class="main-body">
      <a-table :row-selection="rowSelection" :columns="tableColumns" :pagination="false" :data-source="poiList" :scroll="{ x: 900, y: tableHeight }" rowKey="kwaiPoiId">
        <!-- POI信息 -->
        <template slot="poiName" slot-scope="text, record">
          <p><span class="font-weight-bold">门店名称：</span>{{ record.poiName || '无' }}</p>
          <p><span class="font-weight-bold">所属城市：</span>{{ record.poiCity || '无' }}</p>
          <p><span class="font-weight-bold">门店地址：</span>{{ record.poiAddress || '无' }}</p>
          <p><span class="font-weight-bold">经度：</span>{{ record.poiLongitude || '无' }}</p>
          <p><span class="font-weight-bold">纬度：</span>{{ record.poiLatitude || '无' }}</p>
          <p v-if="record.gdId">
            <span class="font-weight-bold">高德POI_ID：</span><a :href="record.gdUrl || ''" target="_blank" v-if="record.gdUrl">{{ record.gdId || '' }}</a
            ><span v-else>{{ record.gdId || '无' }}</span>
          </p>
        </template>
        <!-- POI融合信息 -->
        <template slot="createTime" slot-scope="text, record">
          <div class="flex">
            <div style="margin-right:10px;">
              <p><span class="font-weight-bold">团购名称：</span>{{ record.bizProductName || '无' }}</p>
              <p><span class="font-weight-bold">团购类型：</span>{{ record.productCategoryStr || '无' }}</p>
              <p><span class="font-weight-bold">售价/原价：</span>{{ record.salePriceYuan || 0 }}/{{ record.originPriceYuan || 0 }}</p>
              <p><span class="font-weight-bold">spu状态：</span>{{ record.spuStatusStr || '无' }}</p>
              <p><span class="font-weight-bold">备注：</span>{{ record.spuRemark || '无' }}</p>
            </div>
            <div>
              <p><span class="font-weight-bold">分销推广佣金：</span>{{ record.promotionCommissionYuan || 0 }}</p>
              <p><span class="font-weight-bold">售卖结束时间：</span>{{ record.endTimeMillis || '无' }}</p>
              <p><span class="font-weight-bold">快手申请时间：</span>{{ record.spuApplyTime || '无' }}</p>
              <p><span class="font-weight-bold">快手审出时间：</span>{{ record.spuAuditTime || '无' }}</p>
            </div>
          </div>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleGoods(record, 1, 2)" v-if="record.spuStatus === 5">上架快手</a-button>
          <a-button type="link" @click="handleGoods(record, 0, 2)" v-if="record.spuStatus === 2">下架快手</a-button>
          <a-button type="link" v-if="record.kwaiPoiId" @click="submitKwaiAudit(record)">提交快手审核</a-button>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
    <a-modal v-model="rejectVisible" title="拒绝审核" @cancel="handleRejectCancel" @ok="handleReject">
      <a-input placeholder="请输入拒绝原因" v-model="rejectInfo" />
    </a-modal>
    <quality-submit
      v-model="isShowQuality"
      :qualityList="qualityList"
      :postQualityList="postQualityList"
      :marketingList="marketingList"
      :getProductItemId="productId"
      @onCancel="handleCloseQuality"
      @callback="afterSubmit"
      :type="2"
      :poiIds="kwaiPoiIdList"
    ></quality-submit>
  </a-spin>
</template>

<script>
import { rejectAudit } from '@/service'
import { kwaiSpuForPoi, kwaiSpuSubmitSelect, kwaiSpuUpdateKwaiVisible, kwaiQualitysSpu } from '@/service/ksService'
import upload from '@/components/upload/upload'
import moment from 'moment'
import { columnsConfig } from './columns'
import AddSpuModal from './addSpu/index.vue'
import qualitySubmit from './components/qualitySubmit'
export default {
  name: 'poiManagForSpu',
  components: {
    upload,
    AddSpuModal,
    qualitySubmit
  },

  data() {
    return {
      moment,
      // 新增弹窗
      visible: false,
      judgeId: '',
      // loading是否显示
      isLoading: false,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // table数据查询条件
      search: {
        spuStatus: '',
        gdId: '',
        address: '',
        name: '',
        productItemId: ''
      },
      // poi列表
      poiList: [],
      // 列表总数据条数

      productId: '',
      selectedRowKeys: [],
      rejectVisible: false,
      rejectId: '',
      rejectInfo: '',
      selectLine: [],
      isShowQuality: false,
      qualityList: [],
      marketingList: [],
      productItemId: 0,
      postQualityList: [],
      kwaiPoiIdList: []
    }
  },

  computed: {
    rowSelection() {
      const { selectedRowKeys, onSelectChange } = this
      return {
        selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.matchStatus === 4 || record.matchStatus === 5, // Column configuration not to be checked
            name: record.poiName
          }
        })
      }
    },
    tableColumns() {
      let getColumns = columnsConfig.poiForSpuColumns || []
      return getColumns
    },
    spuStatusList() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '未提审',
          value: 0
        },
        {
          name: '审核中',
          value: 1
        },
        {
          name: '上架',
          value: 2
        },
        {
          name: '审核拒绝',
          value: 3
        },
        {
          name: '下架',
          value: 5
        }
      ]
    }
  },

  methods: {
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    toSpu() {
      this.$router.go(-1)
    },
    // 开启绑定弹窗
    handleOpenBind() {
      this.visible = true
    },
    // 关闭蒙层
    handleCloseModal() {
      this.visible = false
    },
    // 绑定成功回调
    handleUpdateList() {
      this.visible = false
      this.query()
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { spuStatus = '', gdId = '', address = '', name = '', productItemId = 0 } = this.search

      return {
        pageIndex,
        pageSize,
        spuStatus,
        gdId,
        address,
        name,
        productItemId
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, spuStatus = '', gdId = '', address = '', name = '', productItemId = 0 } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          spuStatus,
          gdId,
          address,
          name,
          productItemId
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 获取主播信息列表
     * 具体参数参考 getAnchorInfoListApi 方法
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      kwaiSpuForPoi(this.getParams())
        .then((rs) => {
          console.log(rs)
          this.poiList = Object.freeze(rs.spuListData) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    addBinding() {
      this.$router.push({
        path: '/addSpu',
        query: {
          id: this.productId
        }
      })
    },
    // 拒绝
    refuseDeal(id) {
      this.rejectVisible = true
      this.rejectId = id
    },
    // 拒绝关闭
    handleRejectCancel() {
      this.rejectId = ''
      this.rejectInfo = ''
    },
    handleReject() {
      if (!this.rejectInfo) {
        this.$messageSend.warning('请填写拒绝原因')
      } else {
        rejectAudit({ id: this.rejectId, materialDesc: this.rejectInfo })
          .then((res) => {
            this.$messageSend.success(res)
            this.rejectInfo = ''
            this.rejectId = ''
            this.rejectVisible = false
            this.query()
          })
          .catch((err) => err)
      }
    },
    submitKwaiAudit(row = {}) {
      const { kwaiPoiId = '' } = row
      this.getKwaiQualitysSpu(kwaiPoiId).then(() => {
        this.kwaiPoiIdList = [kwaiPoiId]
        this.isShowQuality = true
      })
    },
    // 查询商品品质
    getKwaiQualitysSpu(poiId = '') {
      const { productId = '' } = this
      return new Promise((resolve, reject) => {
        kwaiQualitysSpu({ productItemId: productId, poiId })
          .then((res = {}) => {
            const { qualityLabels = [], marketingLabels = [] } = res
            console.log(res)
            const self = this
            this.$nextTick(() => {
              self.qualityList = qualityLabels
              self.marketingList = marketingLabels || []
              qualityLabels.forEach((item) => {
                if (item.status === 1) {
                  self.postQualityList.push(item.type)
                }
              })
              resolve(res)
            })
          })
          .catch(() => {
            return reject(new Error('接口出错'))
          })
      })
    },
    handleCloseQuality() {
      this.isShowQuality = false
      this.marketingList = []
      this.postQualityList = []
      this.qualityList = []
      this.search.pageIndex = 1
      this.kwaiPoiIdList = []
    },
    afterSubmit() {
      this.query()
      this.$messageSend.success('操作成功')
      this.handleCloseQuality()
    },
    // 批量提交资质审核
    batchSubmission() {
      const _this = this
      if (!this.selectedRowKeys.length) {
        this.$messageSend.warning('请选择后再进行操作！')
      } else {
        this.$confirm({
          content: '确定批量提交资质审核吗？',
          onOk() {
            // 发送批量操作请求并刷新
            return kwaiSpuSubmitSelect({
              poiIdList: _this.selectedRowKeys,
              productItemId: _this.productId
            })
              .then((res) => {
                _this.$confirm({
                  content: res,
                  onOk() {
                    _this.query()
                    _this.selectedRowKeys = []
                  },
                  onCancel() {}
                })
              })
              .catch((err) => err)
          },
          onCancel() {}
        })
      }
    },
    /**
     * 切换快手上下线状态
     * @param {number} kwaiVisible 1上线，0不上线
     * @param {number} bizProductId 产品id
     * @param {number} type 类型 1=批量 ，2=单个
     * @returns {void}
     */
    handleGoods(items = {}, kwaiVisible = '', type = 0) {
      const { $messageSend, $confirm, query } = this
      const { productItemId = '', kwaiPoiId = '' } = items
      if (type === 1) {
        if (!this.selectedRowKeys.length) {
          this.$messageSend.warning('请选择后再进行操作！')
          return false
        }
      }
      $confirm({
        title: kwaiVisible ? '上线快手' : '下线快手',
        content: kwaiVisible ? '确定要上线吗？' : '操作下线快手后，产品将从快手小程序下线，即在快手C端不显示，是否确认下线',
        onOk: () => {
          // 发送请求
          return kwaiSpuUpdateKwaiVisible({
            kwaiVisible: kwaiVisible,
            productItemId: type === 2 ? productItemId : this.productId,
            poiIdList: type === 2 ? [kwaiPoiId] : this.selectedRowKeys
          })
            .then((rs) => {
              query()
              $messageSend.success('操作成功')
            })
            .catch((err) => err)
        }
      })
    }
  },

  mounted() {
    const { productItemId = '' } = this.$route.query
    this.productId = productItemId
    this.search.productItemId = productItemId
    this.setSearch()
    this.query()
  },

  filters: {
    // 获取直播平台
    getPlatform(val) {
      if (!val) return '无'
      return val === 1 ? '抖音' : '快手'
    }
  }
}
</script>

<style lang="less" scoped>
.anchor-review {
  padding: 16px;
}

// 主播信息弹窗
.anchor-info {
  /deep/ .ant-modal-footer {
    border-top: none;
    padding-bottom: 36px;
    text-align: center;
  }

  //  描述列表样式覆盖
  /deep/ .ant-descriptions-view {
    .ant-descriptions-item-label {
      color: #666666;
    }

    .ant-descriptions-item-content {
      color: #333;
      vertical-align: text-top;
    }
  }
}
.color-f55 {
  color: #f55f4e !important;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
.zzimg {
  /deep/.ant-upload-list-item-list-type-picture-card,
  /deep/.ant-upload-list-picture-card-container {
    width: 30px;
    height: 30px;
    margin: -6px 3px 6px 0;
    padding: 3px;
    border-radius: 2px;
  }
}
p {
  margin-bottom: 5px;
  font-size: 13px;
}
.font-weight-bold {
  font-weight: bold;
  display: inline-block;
}

table tbody td div {
  margin-top: 2px;
}
/deep/ table tbody td a {
  margin-right: 0;
}
.flex {
  display: flex;
}
</style>
